from mongoengine import connect
from app.model.experimentModel import Experiments, Goals, Groups, DocMeta
import re

connect('web_demo', host='mongodb://apps_web_demo:apps_web_demo@115.29.150.66:27017/?authSource=web_demo')


if __name__ == "__main__":
    mapper = {
        "实验名称": {
            "text": "name",
            "sub_item": False
        },
        "实验指标": {
            "text": "goals",
            "sub_item": False
        },
        "对照组": {
            "text": "groups",
            "sub_item": True
        },
        "实验条件": {
            "text": "condition",
            "item": True
        },
        "频率曲线": {
            "text": "line",
            "item": True
        },
        "实验结果": {
            "text": "result",
            "item": True
        },
    }
    datas = []
    with open("data_ori/test.txt", "r") as f:
        temp = {}
        sub_item = {}
        while True:
            a = f.readline()
            if not a:
                break
            if a == '\n':
                temp["groups"].append(sub_item)
                datas.append(temp)
                sub_item = {}
                temp = {}
                continue
            res = re.match(re.compile(r'(\w+)：(.*)\n'), a).groups()
            key = re.match(re.compile(r'(\D+)'), res[0]).groups()[0]
            if "item" in mapper[key] and mapper[key]["item"]:
                sub_item[mapper[key]["text"]] = res[1]
            elif mapper[key]["sub_item"]:
                if sub_item:
                    temp[mapper[key]["text"]].append(sub_item)
                else:
                    temp[mapper[key]["text"]] = []
                sub_item = {}
            else:
                temp[mapper[key]["text"]] = res[1]
    for data in datas:
        res = re.findall(re.compile(
            r"(\w+)（([a-zA-Z0-9^*/=()]+)）"), data["goals"])
        e = Experiments(
            name=data["name"],
            goals=list(map(lambda item: Goals(
                name=item[0], formula=item[1]), res)),
            groups=list(
                map(lambda item: Groups(
                    condition=item["condition"],
                    result=item["result"],
                    line=list(
                        map(
                            lambda it: list(
                                map(float, re.match(r"X([-\d.]+)Y([-\d.]+)",it).groups())
                            ),
                            item["line"].split(";")
                        )
                    )
                ), data["groups"])),
            doc_meta=DocMeta(author="aaaa")
        )
        e.save(signal_kwargs={
            "is_new": True
        })
